package com.kaifamiao.jdbc.transaction;

import java.sql.*;

public class TransactionIsolation {

    public static String translate( int level ) {
        switch ( level ) {
            case 0:
                return "none";
            case 1:
                return "read uncommitted";
            case 2:
                return "read committed";
            case 4:
                return "repeatable read";
            case 8:
                return "serializable";
            default:
                throw new RuntimeException("不支持的隔离级别");
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        /*
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kaifamiao?serverTimezone=Asia/Chongqing";
        String username = "kfm";
        String password = "kfm";
         */

        String driverClassName = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:kaifamiao";
        String username = "kaifamiao";
        String password = "kaifamiao";

        Class.forName( driverClassName );
        Connection conn = DriverManager.getConnection( url, username, password );
        System.out.println( "autocommit: " + conn.getAutoCommit() );
        int level = conn.getTransactionIsolation();
        String levelName = translate( level );
        System.out.println( "transaction isolation level: " + levelName );

        // 关闭事务自动提交
        conn.setAutoCommit( false );
        // 设置事务隔离级别
        conn.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED );

        PreparedStatement stmt = conn.prepareStatement( "DELETE FROM t_pandas WHERE id = ?" );

        stmt.setInt( 1 , 1 );
        stmt.executeUpdate();

        stmt.setInt( 1 , 3 );
        stmt.executeUpdate();

        conn.commit();

        // 启用事务自动提交
        conn.setAutoCommit( true );

        stmt.close();
        conn.close();

    }

}
